package com.jd.admin.controller;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@RequestMapping("/admin")
@RestController
public class ErrorCtr {
    private static final Logger log = LoggerFactory.getLogger(ErrorCtr.class);


    @GetMapping("/product/{id}")
    public String getProduct(@PathVariable String id) {
        return "product id : " + id;
    }

    @GetMapping("/order/{id}")
    public String getOrder(@PathVariable String id) {
        return "order "+id;
    }


    @GetMapping("/test")
    public String importData(MultipartFile file) throws Exception {
        InputStream is = FileMagic.prepareToCheckMagic(file.getInputStream());
        FileMagic fm = FileMagic.valueOf(is);
        log.info("FileMagic:{}", fm);
        Workbook w  = WorkbookFactory.create(file.getInputStream());
        switch (fm){
            case OLE2:
                HSSFSheet ss = (HSSFSheet)w.getSheet("UPLOAD_PIC");
                String str = ss.getRow(0).getCell(0).getStringCellValue();
                log.info("导入前:{}", str);
                Map<String, PictureData> m = getPictures(ss);
                String tt =  str.replace("2-1", "http://1.94.62.148:90/statics/2024/01/18/WechatIMG980_961cee48e9204d388558a686b323ea72.jpg");
                log.info("替换后:{}", tt);
                return "OK";
            case OOXML:
                XSSFSheet ss1 = (XSSFSheet)w.getSheet("UPLOAD_PIC");
                if(ss1 != null) {
                    String str1 = ss1.getRow(0).getCell(0).getStringCellValue();
                    log.info("导入前:{}", str1);
                    Map<String, PictureData> m1 = getPictures(ss1);
                    String tt1 = str1.replace("2-1", "http://1.94.62.148:90/statics/2024/01/18/WechatIMG980_961cee48e9204d388558a686b323ea72.jpg");
                    log.info("替换后:{}", tt1);

                    PictureData p = m1.get("2-1");

                    log.info("suggestFileExtension:{}", p.suggestFileExtension());
                    log.info("getMimeType:{}", p.getMimeType());
                    InputStream inputStream = new ByteArrayInputStream(p.getData());

                    MultipartFile multipartFile = new MockMultipartFile("111", inputStream);
                    log.info("替换后1:{}", tt1);
                }
                return "OK";
            default:
                return "不支持的文件类型";
        }
    }



    public static Map<String, PictureData> getPictures (HSSFSheet sheet)  {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
        for (HSSFShape shape : list) {
            if (shape instanceof HSSFPicture) {
                HSSFPicture picture = (HSSFPicture) shape;
                HSSFClientAnchor cAnchor = picture.getClientAnchor();
                HSSFPictureData pdata = picture.getPictureData();
                String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
                log.info("key222:{}", key);
                map.put(key, pdata);
            }
        }
        return map;
    }

    /**
     * 获取图片和位置 (xlsx)
     * @param sheet
     * @return
     * @throws
     */
    public static Map<String, PictureData> getPictures (XSSFSheet sheet)  {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<POIXMLDocumentPart> list = sheet.getRelations();
        log.info("getRelations:{}", list.size());
        log.info("getRelationParts:{}", sheet.getRelationParts().size());
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getPreferredSize();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    log.info("key111:{}", key);
                    XSSFPictureData pdata = picture.getPictureData();
                    pdata.getData();
                    map.put(key, picture.getPictureData());
                }
            }
        }

        return map;
    }



    @GetMapping("/test11")
    public void importData1(MultipartFile file) throws Exception {
        long startTime = System.currentTimeMillis();
        // 将文件地址和文件名拼接成路径 注意：线上环境不能使用\\拼接
        //File file1 = new File("/Users/caodan/Desktop/work/情绪智能预警系统产品介绍修订版V1.3.pdf");
        try {
            System.out.println(file.getContentType());
            System.out.println(file.getName());
            System.out.println(file.getOriginalFilename());
            // 写入文件
            PDDocument doc = PDDocument.load(file.getInputStream());
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // dpi为144，越高越清晰，转换越慢
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // 将图片写出到该路径下
                String type = "png";
                ImageIO.write(image, type, new File("/Users/caodan/Desktop/img/" + "img_" + (i + 1) + "." + type));

                try {
                    BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
                    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Result result = new MultiFormatReader().decode(bitmap);
                    System.out.println("result: " + result);
                } catch (Exception e) {
                    log.error("BinaryBitmap:{}",e.getMessage());
                }
                //System.out.println("Decoded Data: " + result.getText());

            }
            long endTime = System.currentTimeMillis();
            System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
        } catch (IOException e) {
            log.error("error:{}",e.getMessage());
        }
    }

    @GetMapping("/test2")
    public void importData2(MultipartFile file1) throws Exception {

        System.out.println(file1.getName());
        System.out.println(file1.getContentType());
        // 将文件地址和文件名拼接成路径 注意：线上环境不能使用\\拼接
        try {
           // File file = new File("/Users/caodan/Desktop/img/1_1.png");
            File file = new File("http://1.94.62.148:90/statics/2024/03/16/1_1_86ab8fc475d244a69072d7e09896dd42.png");
            String decodedData = decodeQRCode(file);
            System.out.println("Decoded Data: " + decodedData);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public static String decodeQRCode(File qrCodeimage) throws IOException, NotFoundException {
        BufferedImage bufferedImage = ImageIO.read(qrCodeimage);
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result = new MultiFormatReader().decode(bitmap);
        return result.getText();
    }

    public static String decodeQRCode(InputStream is) throws IOException, NotFoundException {
        BufferedImage bufferedImage = ImageIO.read(is);
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result = new MultiFormatReader().decode(bitmap);
        System.out.println("Decoded Data: " + result);
        return result.getText();
    }

    public static void main(String[] args) {
        System.out.println(LocalDateTime.now());
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(LocalDateTime.now() + " run");
            }
        }, 5, TimeUnit.SECONDS);
        executorService.shutdown();

    }

}
